﻿#include "touchsreen.h"

TouchSreen::TouchSreen(const char *deviceName) {
    memset(m_deviceName, 0, sizeof(m_deviceName));
    memcpy(m_deviceName, deviceName, strlen(deviceName));

    //打开触摸屏
    touchFd = ::open(m_deviceName, O_RDWR);
    if( -1 == touchFd ) {
        perror("open touch error");
        return ;
    }
}

TouchSreen::~TouchSreen() {
    ::close(touchFd);
}

int TouchSreen::waitTouch(int &x, int &y) {

    struct input_event ts_event; //该结构体变量是用来存放读取出来的数据
    int count = 0;

    while(1) {
        memset(&ts_event, 0, sizeof(struct input_event));
        read(touchFd, &ts_event, sizeof(struct input_event)); //read默认是阻塞的，当有数据可读，读到数据，阻塞才解除
        if( ts_event.type == EV_ABS) { //判断是否为触摸屏事件

            if(ts_event.code == ABS_X) { //x轴
                x = ts_event.value;
                count++;
            }

            if(ts_event.code == ABS_Y) {
                y = ts_event.value;
                count++;
            }
        }

        if(2 == count) {
            //std::cout << "rx:" << x << "\try:" << y << std::endl;
            narrowDown(x, y);
            std::cout << "x:" << x << "\ty:" << y << std::endl;
            break;
        }
    }

    return 0;
}

// 缩小范围
void TouchSreen::narrowDown(int &x, int &y) {
    x = (float)x;
    y = (float)y;
    float src_X = 1024, src_Y = 600;
    float dest_X = 800, dest_Y = 480;

    x = (x * 1.0) * (dest_X / src_X);
    x = (int)(x + 0.5); // 四舍五入
    if (x >= 800) {
        x = 800 - 1;
    }

    y = (y * 1.0) * (dest_Y / src_Y);
    y = (int)(y + 0.5); // 四舍五入
    if (y >= 480) {
        y = 480 - 1;
    }
}
